<template>
    <div>
        <!-- 面包屑导航 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>事件列表</el-breadcrumb-item>
        </el-breadcrumb>
        <!-- 卡片 -->
        <el-card class="box-card">
            <!-- 搜索与添加 -->
            <el-row :gutter="20">
                <!-- <el-col :span="8">
                    <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable>
                        <el-button slot="append" icon="el-icon-search"></el-button>
                    </el-input>
                </el-col> -->
                <el-col :span="4">
                    <el-button type="primary" @click="addDialogVisible = true">添加事件</el-button>
                </el-col>
            </el-row>
            <!-- 表格 -->
            <el-table :data="eventList"  stripe >
                <el-table-column type="index"></el-table-column>
                <el-table-column label="年份" prop="year" :filters="yearFilters" :filter-method="filterHandler"></el-table-column>
                <el-table-column label="月份" prop="month" :filters="monthFilters" :filter-method="filterHandler"></el-table-column>
                <el-table-column label="事件" prop="event" :filters="eventFilters" :filter-method="filterHandler"></el-table-column>
                <el-table-column label="操作">
                     <!-- 作用域插槽  在其中放置一些button-->
                    <template slot-scope="scope">
                        <el-button type="primary" size="mini" plain @click="showDetail(scope.row.id)">详情</el-button>
                        <el-button type="warning" size="mini" plain @click="showEditDialog(scope.row.id)">修改</el-button>
                        <el-button type="danger" size="mini" plain @click="removeEventById(scope.row.id)">删除</el-button>
                    </template> 
                </el-table-column>
                <!-- <el-table-column label="状态"> -->
                    <!-- 作用域插槽 -->
                    <!-- <template slot-scope="scope"> -->
                        <!-- <el-switch v-model="scope.row.mg_state" @change="stateChanged(scope.row)"></el-switch> -->
                    <!-- </template>  -->
                <!-- </el-table-column> -->
            </el-table>
            <!-- 分页 -->
            <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="queryInfo.pageNum"
                :page-sizes="[10, 20, 30]"
                :page-size="queryInfo.pageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total">
            </el-pagination>
            <!-- 插入对话框 -->
            <el-dialog
                title="新增事件"
                :visible.sync="addDialogVisible"
                width="50%"
                @close="addDialogClosed">
                <!-- 对话框内容主体 -->
                <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="70px">
                    <el-form-item label="年份" prop="year">
                        <el-input v-model="addForm.year"></el-input>
                    </el-form-item>
                    <el-form-item label="月份" prop="month">
                        <el-input v-model="addForm.month"></el-input>
                    </el-form-item>
                    <el-form-item label="事件" prop="event">
                        <el-input v-model="addForm.event"></el-input>
                    </el-form-item>
                </el-form>
                <!-- 对话框底部 -->
                <span slot="footer" class="dialog-footer">
                    <el-button @click="addDialogVisible = false">取 消</el-button>
                    <el-button type="primary" @click="addEvent">确 定</el-button>
                </span>
            </el-dialog> 
            <!-- 修改对话框 -->
            <el-dialog
                title="修改事件"
                :visible.sync="editDialogVisible"
                width="50%"
                @close="editDialogClosed">
                <!-- 对话框内容主体 -->
                <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="70px">
                    <el-form-item label="年份" prop="year"> <!--prop 是在editFormRule中用的-->
                        <el-input v-model="editForm.year"></el-input>
                    </el-form-item>
                    <el-form-item label="月份" prop="month">
                        <el-input v-model="editForm.month"></el-input>
                    </el-form-item>
                    <el-form-item label="事件" prop="event">
                        <el-input v-model="editForm.event"></el-input>
                    </el-form-item>
                </el-form>
                <!-- 对话框底部 -->
                <span slot="footer" class="dialog-footer">
                    <el-button @click="editDialogVisible = false">取 消</el-button>
                    <el-button type="primary" @click="editEventInfo">确 定</el-button>
                </span>
            </el-dialog> 
            <!-- 删除提示框 -->
        </el-card>
    

    </div>
</template>

<script>
export default {
    data() {
        // 验证年份的规则
        var checkYear = (rule, value, callback) => {
            // 正则 从1000年到2999年
            const regYear = /^[12][0-9]{3}$/; 
            if (regYear.test(value)) {
                // 合法
                return callback();
            }
            callback(new Error('请输入正确年份'));
        }
        return {
            // 参数
            queryInfo: {
                pageNum:1,
                pageSize:20,
                query:''
            },
            eventList: [
                // {id: "172", year:"1818", month:"5月5日", event:"马克思诞生于德国特里尔市"},
                // {id: "173", year:"1820", month:"11月28日", event:"恩格斯诞生于德国巴门市"}
            ],
            yearFilters:[],
            monthFilters:[],
            eventFilters:[],
            total: 0,
            // 控制添加事件的显示与隐藏
            addDialogVisible: false,
            editDialogVisible: false,
            // 添加事件的表单数据
            addForm: {
                year: "",
                month:"",
                event:""
            },
            editForm: {
                year: "",
                month:"",
                event:""
            },
            // 添加表单的验证规则对象
            addFormRules:{
                year:[
                    { required: true, message: '请输入年份', trigger: 'blur' },
                    { min: 4, max: 4, message: '长度在4个字符', trigger: 'blur' },
                    { validator: checkYear, trigger: 'blur' } // 自定义校验规则
                ],
                month:[
                    { required: true, message: '请输入月份', trigger: 'blur' },
                    { min: 2, max: 50, message: '长度在50个字符', trigger: 'blur' }
                ],
                event:[
                    { required: true, message: '请输入事件', trigger: 'blur' },
                    { min: 2, max: 100, message: '长度在2~100个字符', trigger: 'blur' }
                ]
            },
            editFormRules:{
                year:[
                    { required: true, message: '请输入年份', trigger: 'blur' },
                    { min: 4, max: 4, message: '长度在4个字符', trigger: 'blur' },
                    { validator: checkYear, trigger: 'blur' } // 自定义校验规则
                ],
                month:[
                    { required: true, message: '请输入月份', trigger: 'blur' },
                    { min: 2, max: 50, message: '长度在50个字符', trigger: 'blur' }
                ],
                event:[
                    { required: true, message: '请输入事件', trigger: 'blur' },
                    { min: 2, max: 100, message: '长度在2~100个字符', trigger: 'blur' }
                ]
            }
        }
    },
    created() {
        this.getEventList()
    },
    methods: {
        async getEventList() {
            const {data:res} = await this.$http.get("event/selectAll", {params: this.queryInfo})
            if (res.code != 200) return this.$message.error("获取事件列表失败!");
            this.eventList = res.data
            for (let i = 0; i < this.eventList.length; i++) {
                const cur_event = this.eventList[i];

                var yearObj = new Object();
                yearObj.text = cur_event.year;
                yearObj.value = cur_event.year;
                this.yearFilters.push(yearObj);

                var monthObj = new Object();
                monthObj.text = cur_event.month;
                monthObj.value = cur_event.month;
                this.monthFilters.push(monthObj);

                var eventObj = new Object();
                eventObj.text = cur_event.event;
                eventObj.value = cur_event.event;
                this.eventFilters.push(eventObj);
            }
            // this.eventList = res.data.eventList;
            // this.total = res.data.total;
        },
        // 监听pagesize改变的事件
        handleSizeChange(newSize) {
            // console.log(newSize)
            this.queryInfo.pageSize = newSize;
            // this.getEventList();
        },
        // 监听pageNumber改变的事件 , 不是pageNumber而是改变页码操作
        handleCurrentChange(newPage) {
            console.log(newPage)
            this.queryInfo.pageNum = newPage;
             // this.getEventList();
        },
        // 监听switch改变事件
        async stateChanged(eventInfo) {
            // console.log(eventInfo);
            // const {data:res} = await this.$http.put(`updateEventState/${eventInfo.id}/state/${eventInfo.mg_state}`);
            // if (res.meta.status !== 200) {
            //     eventInfo.mg_state = !eventInfo.mg_state;
            //     return this.$message.error("更新状态失败")
            // }   
        },
        // 对话框关闭够重置
        addDialogClosed() {
            this.$refs.addFormRef.resetFields();
        },
        editDialogClosed() {
            this.$refs.editFormRef.resetFields();
        },
        // 点击确定添加新事件
        addEvent() {
            this.$refs.addFormRef.validate(async valid => {
                // valid 是根据rules="addFormRules" 是否校验通过
                if (!valid) return this.$message.error("填写的信息不符合规范");
                // 发起请求
                const {data:res} = await this.$http.post('event/insert', this.addForm);
                if (res.code != 200) {
                    this.$message.error("添加失败");
                }
                this.$message.success("添加成功");
                // 关闭添加对话框
                this.addDialogVisible = false;
                // 重新获取页面列表
                this.getEventList()
            })
        },
        // 展示编辑事件的对话框（修改）
        async showEditDialog(id) {
            this.editDialogVisible = true;
            const{data:res} = await this.$http.get("event/selectOne", {params:{"id":id}});
            this.editForm = res.data;
        },
        // 根据id删除事件
        async removeEventById(id) {
            // 弹框提示
            const conformRes = await this.$confirm('此操作将删除该条, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'  // 图标
            }).catch(err => {
                return err
            }) 
            // 如果用户确认则返回confirm串 取消返回的是cancel
            // console.log(conformRes)
            if (conformRes !== "confirm") {
                return this.$message.info("已经取消删除");
            }
            const{data:res} = await this.$http.post("event/deleteById", {id:id});
            if (res.code !== 200) {
                return this.$message.error("删除失败");
            }
            this.$message.success("删除成功");
            this.getEventList();
        },
        async editEventInfo () {
            this.$refs.editFormRef.validate(async valid =>{

                if (!valid) return
                // 发起请求
                const {data:res} = await this.$http.post("event/update", this.editForm);
                console.log(res)
                if (res.code !== 200) {
                    return this.$message.error("更新失败");
                }
                // 关闭对话框
                this.editDialogVisible = false;
                // 刷新列表
                this.getEventList();
                // 提示更新成功
                this.$message.success("更新成功");
            } )
        },
        // 点击每行详情跳转详情页面并传递id
        showDetail(id) {
            this.$router.push({
                    path:"/eventDetail",
                    query:{
                        "eventId":id
                    }
                })
        },
        // 表格过滤函数
        filterHandler(value, row, column) {
            const property = column['property'];
            return row[property] === value;
        }
    }
}
</script>

<style lang="less" scoped>
    .box-card {
        line-height: 0%;
        text-align: left;
    }
</style>